<template>
  <div class="SQLCodeAll">

    <el-container>
      <el-aside width="300px">数据库-表</el-aside>
      <el-container>
        <el-header>
          <div class="title">SQLCode Header</div>
          <div class="flex">

            <el-select v-model="sqlVal" placeholder="请选择" size="mini">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled">
              </el-option>
            </el-select>
            <el-button size="mini" type="success" @click="runCode"><i class="el-icon-caret-right"></i>执行</el-button>
            <el-button type="primary" size="mini" icon="el-icon-magic-stick" @click="autoFormatSelection">格式化</el-button>
          </div>
        </el-header>
        <el-main>
          <!-- <codemirror v-show="sqlFlag" v-model="code" :options="cmOptions" @ready="onCmReady" ref="codemirror"></codemirror> -->
          <textarea ref="mycode" v-model="code" placeholder="按Ctrl键进行代码提示" class="codesql" style="height:600px;width:100%;" />

          <div class="result">
            <el-table :data="tableData" style="width: 100%" v-if="tableData&&tableData.length>0">
              <el-table-column :prop="item.prop" :label="item.name" v-for="(item,index) in tableInfo" :key="index">
              </el-table-column>

            </el-table>
          </div>
        </el-main>

      </el-container>
    </el-container>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》'
import { codemirror } from "vue-codemirror";
import "codemirror/lib/codemirror.css";
import "codemirror/theme/dracula.css";
import "codemirror/mode/sql/sql.js"; // 对于sql模式的支持
import "codemirror/keymap/sublime.js";
import "codemirror/addon/hint/show-hint.css";
import "codemirror/addon/hint/show-hint.js";
import "codemirror/addon/hint/sql-hint.js";
// import sqlFormatter from "sql-formatter";
import { format } from "sql-formatter";

import "codemirror/theme/ambiance.css";
import "codemirror/lib/codemirror.css";
import "codemirror/addon/hint/show-hint.css";

const CodeMirror = require("codemirror/lib/codemirror");
require("codemirror/addon/edit/matchbrackets");
require("codemirror/addon/selection/active-line");
require("codemirror/mode/sql/sql");
require("codemirror/addon/hint/show-hint");
require("codemirror/addon/hint/sql-hint");

// 设置编辑器的最小高度是200
const MIN_HEIGHT = 350;
export default {
  name: "",
  // import引入的组件需要注入到对象中才能使用
  components: { codemirror },
  data() {
    // 这里存放数据
    return {
      sqlFlag: false,
      sqlVal: "mysql",
      options: [
        { label: "mysql", value: "mysql" },
        { label: "plsql", value: "plsql", disabled: true },
        { label: "sql", value: "sql", disabled: true },
        { label: "db2", value: "db2", disabled: true },
      ],
      code: "INSERT INTO students (id, class_id, name, gender, score) VALUES (1, 1, '小明', 'F', 99) ON DUPLICATE KEY UPDATE name='小明', gender='F', score=99;",
      cmOptions: {
        mode: "text/x-sql", //实现Java代码高亮
        lineNumbers: true,
        theme: "", //dracula
        keyMap: "sublime",
        extraKeys: { Ctrl: "autocomplete" },
        lineWrapping: true, //是否换行
        foldGutter: true, //是否折叠
        gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], //添加行号栏，折叠栏
      },
      position_initail_y: 0,
      position_y: 0,
      tableData: [],
      tableInfo: [],
    };
  },
  // 监听属性 类似于data概念
  computed: {
    codemirror() {
      return this.$refs.codemirror.codemirror;
    },
  },
  // 监控data中的数据变化
  watch: {},
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    let me = this;
    /* this.$nextTick(() => {
      me.sqlFlag = true;
      this.codemirror.setSize("height", MIN_HEIGHT);
      // 获取当前编辑器的初始高度
      let height = this.$refs.codemirror.$el.offsetHeight;

      console.log("编辑器初始高度：", height);
    }, 1000); */
    setTimeout(() => {
      // me.autoFormatSelection();
    }, 1100);

    const mime = "text/x-mariadb";
    // let theme = 'ambiance'//设置主题，不设置的会使用默认主题
    this.editor = CodeMirror.fromTextArea(this.$refs.mycode, {
      mode: mime, // 选择对应代码编辑器的语言，我这边选的是数据库，根据个人情况自行设置即可
      indentWithTabs: true,
      smartIndent: true,
      lineNumbers: true,
      matchBrackets: true,
      // theme: 'base16-light',
      // autofocus: true,
      extraKeys: { Ctrl: "autocomplete" }, // 自定义快捷键
      hintOptions: {
        // 自定义提示选项
        tables: {
          users: ["1112", "123123", "124124"],
          countries: ["124", "124124", "1"],
        },
      },
    });
    this.editor.on("cursorActivity", () => {
      this.editor.showHint();
    });
  },
  // 方法集合
  methods: {
    onCmReady(cm) {
      cm.on("keypress", () => {
        cm.showHint();
      });
    },
    getEditorHeight() {
      return this.$refs.codemirror.$el.offsetHeight;
    },
    runCode() {
      let str = this.codemirror.getValue();
      console.log("sql code", str);
      this.$axios
        .post("http://localhost:3001/api/querySQL", { sql: str })
        .then((req) => {
          console.log("req.data", req.data);
        });
    },
    //格式化
    autoFormatSelection() {
      let str = format(this.codemirror.getValue(), {
        language: "sql",
      });
      this.codemirror.setValue(str);
    },
  },
};
</script>

<style>
.SQLCodeAll {
  height: 100%;
}
.el-header,
.el-footer {
  background-color: #b3c0d1;
  color: #333;
  text-align: center;
  /* line-height: 60px; */
}

.el-aside {
  background-color: #d3dce6;
  color: #333;
  text-align: center;
  /* line-height: 200px; */
  height: 100%;
}

.el-main {
  background-color: #e9eef3;
  color: #333;
  text-align: center;
  /* line-height: 160px; */
}

.el-container {
  height: 100%;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  /* line-height: 260px; */
}

.el-container:nth-child(7) .el-aside {
  /* line-height: 320px; */
}
/* 
.editor__run {
  text-align: center;
  background-color: #d8f0f5;
}
.editor__drag {
  background: #3d444c;
  user-select: none;
  cursor: row-resize;
  text-align: center;
  line-height: 20px;
}
.arrow-v {
  background-color: #161b1e;
  display: inline-block;
  width: 2rem;
  line-height: inherit;
}
.CodeMirror-sizer {
  text-align: left;
} */
.result {
  margin-top: 10px;
  width: 100%;
  flex: 1;
}
</style>
